package com.logic.config.netty.web.service;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSONObject;

import com.logic.config.netty.web.util.SessionHolder;
import com.comment.pojo.domain.logic.core.PvpMatch;
import com.logic.modular.game.core.service.MatchServiceImpl;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Service
public class MessageService {
    private static final ConcurrentHashMap<String, Integer> messageId = new ConcurrentHashMap<>();
    public static final ConcurrentHashMap<Integer, Object> messageInfo = new ConcurrentHashMap<>();

    public static Integer sendMessageToUser(Long uid, JSONObject jsonObject) {
        Integer i = messageId.get("messageId");
        if (i == null) {
            i = 0;
        }
        ++i;

        try {
            Channel channel = SessionHolder.channelMap.get(uid);
            if (channel == null) {
                return null;
            }
            jsonObject.put("id", i);
            jsonObject.put("toUser", uid);
            String messageStr = JSONObject.toJSONString(jsonObject);

            TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(messageStr);
            channel.writeAndFlush(textWebSocketFrame);

            messageId.put("messageId", i);
            messageInfo.put(i, jsonObject);
        } catch (Exception e) {
            log.error("sendMessageToUser error:", e);
        }
        return i;
    }

    public static void sendMessageToMatch(Set<Long> playerIds, JSONObject message) {
        for (Long playerId : playerIds) {
            sendMessageToUser(playerId, message);
        }
    }

    public static void sendMessageToMatch(Long matchId, JSONObject message) {
        MatchServiceImpl bean = SpringUtil.getBean(MatchServiceImpl.class);
        PvpMatch pvpMatch = bean.getById(matchId);
        sendMessageToMatch(pvpMatch.getPlayerIds(), message);
    }

    public static JSONObject updateJsonObject(String name, Object value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(name + "-u", value);
        return jsonObject;
    }
}
